package server.phone.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import server.phone.dao.SaleAndPdtDAO;
import server.phone.dao.SaleRecordDAO;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;
import com.utopia84.model.Saleandpdt;
import com.utopia84.model.Salerecord;

public class SetSaleAndPdtServlet extends ActionSupport {
	private static final long serialVersionUID = -7811568044252827351L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public SetSaleAndPdtServlet(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
	}

	 
	public void doPost()	throws  IOException {
		String saleAndPdts = request.getParameter("saleAndPdts");
		List<Saleandpdt> records = new ArrayList<Saleandpdt>();
		Saleandpdt record;
		String status = "Sent";
		try {
			SaleAndPdtDAO srd = new SaleAndPdtDAO();
			JSONArray array = JSONArray.fromObject(saleAndPdts);
			for (int i = 0; i < array.size(); i++) {
				JSONObject rs = array.getJSONObject(i);
				System.out.println(rs.toString());
				if (srd.isDrink(rs.getString("pdtCode"))) {
					status = "Done";
				} else {
					status = "Sent";
				}
				
				record = new Saleandpdt(Integer.parseInt(rs.getString("contactNumber")),
						Integer.parseInt(rs.getString("id")),rs.getString("salerecordId"),
						rs.getString("pdtCode"),rs.getString("pdtName"),
						Integer.parseInt(rs.getString("number")),Float.parseFloat(rs.getString("price")),
						rs.getString("status"),Integer.parseInt(rs.getString("priority")),rs.getString("otherspec"),
						rs.getString("otherspec1"),rs.getString("otherspec2"),
						rs.getString("createTime"),rs.getString("closeTime")
						);
				records.add(record);
			}

			srd.saveSaleAndPdt(records);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JSONObject jObject = new JSONObject();
		try {
			jObject.put("ret", "success");
		} catch (Exception e) {
			jObject.put("ret", "error");
		}
		jObject.put("ret", "success");

		PrintWriter out = response.getWriter();
		out.println(jObject);
		out.flush();
		out.close();
	}

}
